local internet = require("internet")
local colors = require("lib.graphics.colors")
local ar = require("lib.graphics.ar")
local screen = require("lib.utils.screen")
local time = require("lib.utils.time")
local parser = require("lib.utils.parser")
local computer = require("computer")
--

local toolbar = {}

local hudObjects = {}

function toolbar.changeColor(glasses, backgroundColor, primaryColor, accentColor)
    for i = 1, #hudObjects do
        if hudObjects[i] then
            if hudObjects[i].glasses ~= nil then
                if hudObjects[i].glasses.address == glasses then
                    if backgroundColor ~= nil then
                        for j = 1, #hudObjects[i].static do
                            hudObjects[i].static[j].setColor(screen.toRGB(backgroundColor))
                        end
                    end
                    if primaryColor ~= nil then
                        if hudObjects[i].dynamic.xpbar then
                            hudObjects[i].dynamic.xpbar.setColor(screen.toRGB(primaryColor))
                        end
                        if hudObjects[i].dynamic.topstrip then
                            hudObjects[i].dynamic.topstrip.setColor(screen.toRGB(primaryColor))
                        end
                        if hudObjects[i].dynamic.diagonal then
                            hudObjects[i].dynamic.diagonal.setColor(screen.toRGB(primaryColor))
                        end
                        if hudObjects[i].dynamic.rightstrip then
                            hudObjects[i].dynamic.rightstrip.setColor(screen.toRGB(primaryColor))
                        end
                        if hudObjects[i].dynamic.clockEdge then
                            hudObjects[i].dynamic.clockEdge.setColor(screen.toRGB(primaryColor))
                        end
                        if hudObjects[i].dynamic.realtime then
                            hudObjects[i].dynamic.realtime.setColor(screen.toRGB(primaryColor))
                        end
                    end
                    if accentColor ~= nil then
                        if hudObjects[i].dynamic.clock then
                            hudObjects[i].dynamic.clock.setColor(screen.toRGB(accentColor))
                        end
                    end
                end
            end
        end
    end
end

local realtime = 0
local requestCounter = 100

local hExpBar = 5  
local clockWidth = 88
local clockheight = 10
local rightTriangleSide = 30
local middleTriangleSide = 9

-- 公用静态元素创建函数
local function createCommonStaticElements(hudObject, x, y, w, h, borderColor, primaryColor)
	-- XP条 (四边形)
	table.insert(hudObject.static, ar.rectangle(hudObject.glasses, {x, y+12}, w, 5, primaryColor, 0.5))
	-- XP条左侧装饰 (三角形 - 实际上是四边形的一种特殊形式)
    table.insert(hudObject.static, ar.triangle(hudObject.glasses, 
        {x, y+13}, 
        {x, y+13+hExpBar}, 
        {x+hExpBar, y+13+hExpBar}, 
        borderColor))
    -- XP条右侧装饰 (三角形)
    table.insert(hudObject.static, ar.triangle(hudObject.glasses, 
        {x+w+1-hExpBar, y+12}, 
        {x+w+1, y+12+hExpBar}, 
        {x+w+1, y+12}, 
        borderColor))


    -- 装备矩形 (四边形)
    table.insert(hudObject.static, ar.rectangle(hudObject.glasses, {x+1, y-7}, w, 20, borderColor, 0.6))
    
    -- 顶部斜角边框 (四边形)
    table.insert(hudObject.static, ar.quad(hudObject.glasses, 
        {x+2, y-10}, 
        {x, y+3-10}, 
        {x+w+2, y+3-10}, 
        {x+w, y-10}, 
        borderColor))
    
    -- 中间分隔线 (矩形)
    table.insert(hudObject.static, ar.rectangle(hudObject.glasses, {x, y+12}, w, 1, borderColor))
    -- 底部分隔线 (矩形)
    table.insert(hudObject.static, ar.rectangle(hudObject.glasses, {x, y+17}, w, 3, borderColor))
    -- 中间三角形装饰 (四边形)
    table.insert(hudObject.static, ar.quad(hudObject.glasses, 
        {x+w/2-middleTriangleSide+5, y+3}, 
        {x+w/2-2*middleTriangleSide+5, y+3+middleTriangleSide}, 
        {x+w/2+2*middleTriangleSide-3, y+3+middleTriangleSide}, 
        {x+w/2+middleTriangleSide-3, y+3}, 
        borderColor))
	table.insert(hudObject.static, ar.quad(hudObject.glasses, 
        {x+w/2-middleTriangleSide+6, y+3}, 
        {x+w/2-2*middleTriangleSide+6, y+3+middleTriangleSide}, 
        {x+w/2+2*middleTriangleSide-4, y+3+middleTriangleSide}, 
        {x+w/2+middleTriangleSide-4, y+3}, 
        primaryColor))
	table.insert(hudObject.static, ar.quad(hudObject.glasses, 
        {x+w/2-middleTriangleSide+7, y+3}, 
        {x+w/2-2*middleTriangleSide+7, y+3+middleTriangleSide}, 
        {x+w/2+2*middleTriangleSide-5, y+3+middleTriangleSide}, 
        {x+w/2+middleTriangleSide-5, y+3}, 
        borderColor))
	-- 顶部装饰条纹 (矩形)
    hudObject.dynamic.topstrip = ar.rectangle(hudObject.glasses, {x+2, y-9}, w-2, 1, primaryColor)
end
-- 左对齐（居中）模式专用元素
local function createLeftAlignedElements(hudObject, x, y, w, h, borderColor, primaryColor, accentColor)
    -- 左侧边框 (矩形)
     table.insert(hudObject.static, ar.rectangle(hudObject.glasses, {x, y-7}, 2, h+10, borderColor))
   -- 右侧三角形装饰 (四边形)
    table.insert(hudObject.static, ar.quad(hudObject.glasses, 
        {x+w, y-10}, 
        {x+w, y+h}, 
        {x+w+rightTriangleSide, y+h}, 
        {x+w+rightTriangleSide, y+rightTriangleSide-10}, 
        borderColor))
    -- 对角线条纹 (四边形)
    hudObject.dynamic.diagonal = ar.quad(hudObject.glasses, 
        {x+w, y-9}, 
        {x+w, y+2-10}, 
        {x+w+rightTriangleSide-1, y+1+rightTriangleSide-10},  
        {x+w+rightTriangleSide-1, y+rightTriangleSide-10}, 
        primaryColor)
    -- 右侧条纹 (矩形)
    hudObject.dynamic.rightstrip = ar.rectangle(hudObject.glasses, 
        {x+w+rightTriangleSide-2, y+rightTriangleSide-10}, 
        1, h-rightTriangleSide+10, primaryColor)
    -- 时钟底座 (矩形)
    table.insert(hudObject.static, ar.rectangle(hudObject.glasses, {x+w+3, y+6}, clockWidth+2, clockheight+2, borderColor))
    -- 时钟边缘 (矩形)
    hudObject.dynamic.clockEdge = ar.rectangle(hudObject.glasses, {x+w+4, y+7}, clockWidth, clockheight, primaryColor)
    -- 时钟面板 (矩形)
    table.insert(hudObject.static, ar.rectangle(hudObject.glasses, {x+w+5, y+8}, clockWidth-2, clockheight-2, borderColor))
    -- 时钟文本 (点位置)
    hudObject.dynamic.clock = ar.text(hudObject.glasses, "", {x+w+7, y+10}, accentColor, 0.65)
    
    -- 实时时间文本 (带阴影效果)
    local realtimeX, realtimeY = x+w+3.5, y+27
    -- 阴影文本 (黑色背景)
    hudObject.dynamic.realtime_shadow = ar.text(hudObject.glasses, "", {realtimeX+0.5, realtimeY+0.5}, borderColor, 0.8)
    -- 主文本
    hudObject.dynamic.realtime = ar.text(hudObject.glasses, "", {realtimeX, realtimeY}, primaryColor, 0.8)
	
end
-- 右对齐模式专用元素
local function createRightAlignedElements(hudObject, x, y, w, h, borderColor, primaryColor, accentColor)
    -- 右侧装饰边缘 (矩形)
	table.insert(hudObject.static, ar.rectangle(hudObject.glasses, {x+w, y-7}, 2, h+7, borderColor))
	-- 左侧三角形装饰
    table.insert(hudObject.static, ar.quad(hudObject.glasses, 
        {x-12, y+4}, 
        {x-12, y+h}, 
        {x+2, y+h}, 
        {x+2, y-10}, 
        borderColor))
	-- 对角线条纹 (四边形)
    hudObject.dynamic.diagonal = ar.quad(hudObject.glasses, 
        {x-11, y+4},
        {x-11, y+5},
        {x+2, y-8},
        {x+2, y-9},
        primaryColor)
    -- 左侧条纹 (矩形)
    hudObject.dynamic.rightstrip = ar.rectangle(hudObject.glasses, {x-11, y+4}, 1, h-rightTriangleSide+26, primaryColor)

    local clockX = x - clockWidth - 5
	-- 左侧时钟底座 (矩形)
    table.insert(hudObject.static, ar.rectangle(hudObject.glasses, {clockX, y+8}, clockWidth+2, clockheight+2, borderColor))
    -- 时钟边缘 (矩形)
    hudObject.dynamic.clockEdge = ar.rectangle(hudObject.glasses, {clockX+1, y+9}, clockWidth, clockheight, primaryColor)
    -- 时钟面板 (矩形)
    table.insert(hudObject.static, ar.rectangle(hudObject.glasses, {clockX+2, y+10}, clockWidth-2, clockheight-2, borderColor))
    -- 时钟文本 (点位置)
    hudObject.dynamic.clock = ar.text(hudObject.glasses, "", {clockX+4, y+12}, accentColor, 0.65)

	-- 左侧时钟底座 (矩形)
    table.insert(hudObject.static, ar.rectangle(hudObject.glasses, {x-33, y+20}, 22, 22, borderColor))
    -- 时钟边缘 (矩形)
    hudObject.dynamic.clockEdge = ar.rectangle(hudObject.glasses, {x-32, y+21}, 20, 20, primaryColor)
    -- 时钟面板 (矩形)
    table.insert(hudObject.static, ar.rectangle(hudObject.glasses, {x-31, y+22}, 18, 18, borderColor))
    
    -- 实时时间文本 (带阴影效果)
    local realtimeX, realtimeY = x-30, y+29
    -- 阴影文本 (黑色背景)
    hudObject.dynamic.realtime_shadow = ar.text(hudObject.glasses, "", {realtimeX+0.5, realtimeY+0.5}, borderColor, 0.65)
    -- 主文本
    hudObject.dynamic.realtime = ar.text(hudObject.glasses, "", {realtimeX, realtimeY}, primaryColor, 0.65)
end

-- 整合HUD元素创建
local function createHudElements(hudObject, x, y, w, h, borderColor, primaryColor, accentColor)
    -- 创建公用元素
    createCommonStaticElements(hudObject, x, y, w, h, borderColor, primaryColor)
    
    -- 根据对齐模式创建特定元素
    if hudObject.rightAlign then
        createRightAlignedElements(hudObject, x, y, w, h, borderColor, primaryColor, accentColor)
    else
        createLeftAlignedElements(hudObject, x, y, w, h, borderColor, primaryColor, accentColor)
    end
    
    -- 调试内存显示（开发模式）
    if DEBUG then
        -- 内存文本 (点位置)
        hudObject.dynamic.memory = ar.text(hudObject.glasses, "", {x+w/2+10, y-6}, primaryColor, 0.8)
    end
end

function toolbar.widget(glasses)
    if #hudObjects == 0 then
        for i = 1, #glasses do
            if glasses[i][1] == nil then
                error("Must provide glass proxy for toolbar.")
            end
            table.insert(
                hudObjects,
                {
                    static = {},
                    dynamic = {},
                    glasses = glasses[i][1],
                    resolution = glasses[i][2] or {2560, 1440},
                    scale = glasses[i][3] or 3,
                    offset = glasses[i][4] or 0,
                    borderColor = glasses[i][5] or colors.darkGray,
                    primaryColor = glasses[i][6] or colors.electricBlue,
                    accentColor = glasses[i][7] or colors.magenta,
                    rightAlign = glasses[i][8] or false  -- 右对齐配置
                }
            )
        end
    end
    
    -- 获取当前时间
    local timeString = os.date()
    local day = timeString:sub(1, 2)
    local month = timeString:sub(4, 5)
    local year = math.floor(((((os.time() / 60) / 60) / 24) / 365) + 1)
    local date = math.floor((((os.time() / 60) / 60) / 24) - ((year - 1) * 365))
    local hours = timeString:sub(10, #timeString - 3)
    timeString = hours .. " | " .. "Day " .. date .. " Year " .. year
    
    -- 每100次更新请求一次实时时间
    if requestCounter == 100 then
        pcall(function()
            realtime = time.realtime()
        end)
        requestCounter = 1
    end
    
    for i = 1, #hudObjects do
        if hudObjects[i] then
            local resolution = screen.size(hudObjects[i].resolution, hudObjects[i].scale)
            local w = 183  -- 工具栏宽度
            local h = 42   -- 工具栏高度
            
            -- 根据对齐模式计算位置
            local x
            if hudObjects[i].rightAlign then
                -- 右对齐：放在屏幕右下角
                -- 位置: (屏幕宽度 - 工具栏宽度 - 5, 屏幕底部 - 工具栏高度)
                x = resolution[1] / 2 - w / 2
            else
                -- 左对齐（居中）：放在屏幕中央
                -- 位置: (屏幕宽度/2 - 工具栏宽度/2, 屏幕底部 - 工具栏高度)
                x = resolution[1] / 2 - w / 2
            end
            local y = resolution[2] - h  -- 工具栏Y坐标
            
            -- 首次创建元素
            if #hudObjects[i].static == 0 and #hudObjects[i].glasses ~= nil then
                createHudElements(
                    hudObjects[i], 
                    x, y, w, h,
                    hudObjects[i].borderColor,
                    hudObjects[i].primaryColor,
                    hudObjects[i].accentColor
                )
            end
            
            -- 更新时间显示
            hudObjects[i].dynamic.clock.setText(timeString)
            
            -- 更新实时时间（带时区偏移）和阴影
            local formattedTime = time.offset(hudObjects[i].offset, realtime)
            if formattedTime then
                hudObjects[i].dynamic.realtime.setText(formattedTime)
                -- 同时更新阴影文本
                if hudObjects[i].dynamic.realtime_shadow then
                    hudObjects[i].dynamic.realtime_shadow.setText(formattedTime)
                end
            end
            
            -- 调试内存使用
            if DEBUG then
                local maxMemory = computer.totalMemory()
                local usedMemory = maxMemory - computer.freeMemory()
                hudObjects[i].dynamic.memory.setText(
                    "Memory used: "..parser.percentage(usedMemory/maxMemory))
            end
        end
    end
    requestCounter = requestCounter + 1
end

function toolbar.remove(glassAddress)
    for i = 1, #hudObjects do
        local hudObject = hudObjects[i]
        if hudObject then
            local glasses = hudObject.glasses
            if glasses ~= nil then
                if glasses.address == glassAddress then
                    -- 移除静态元素
                    for j = 1, #hudObjects[i].static do
                        hudObjects[i].glasses.removeObject(hudObjects[i].static[j].getID())
                    end
                    hudObjects[i].static = {}
                    
                    -- 移除动态元素
                    for name, value in pairs(hudObjects[i].dynamic) do
                        hudObjects[i].glasses.removeObject(hudObjects[i].dynamic[name].getID())
                    end
                    hudObjects[i].dynamic = {}
                    
                    -- 清理对象
                    hudObjects[i] = nil
                end
            end
        end
    end
end

return toolbar